#!/usr/bin/env python

from __future__ import print_function
import os
import sys
import subprocess
import re

re_needso = re.compile(r'^.*\(NEEDED\)\s+Shared library: \[lib(.*)\.so\]\s*$')

blacklist_libs = (
  'c',
  'stdc++',
  'dl',
  'python2.7',
  'sdl',
  'sdl_image',
  'sdl_ttf',
  'z',
  'm',
  'GLESv2',
  'jpeg',
  'png',
  'log',
)

found_libs = []
sofiles = [ ]

for directory in sys.argv[2:]:

  for fn in os.listdir(directory):
    if fn[-3:] != '.so':
      continue

    fn = os.path.join(directory, fn)

    print (fn)
    continue

    with open(fn) as f:
      needed_libs = [lib for lib in {ln.strip() for ln in f} if lib not in blacklist_libs and lib not in found_libs]

      while needed_libs:
        print('need libs:\n\t' + '\n\t'.join(needed_libs))

        start_needed_libs = needed_libs[:]
        found_sofiles = []

        with open(dirfn) as f:
          for libdir in f:
            if not needed_libs:
              break

            libdir = libdir.strip()
            print('scanning %s' % libdir)
            for lib in needed_libs[:]:
              if lib in found_libs:
                continue

              if lib.endswith('.a'):
                needed_libs.remove(lib)
                found_libs.append(lib)
                continue

              lib_a = 'lib' + lib + '.a'
              libpath_a = os.path.join(libdir, lib_a)
              lib_so = 'lib' + lib + '.so'
              libpath_so = os.path.join(libdir, lib_so)
              plain_so = lib + '.so'
              plainpath_so = os.path.join(libdir, plain_so)

              sopath = None
              if os.path.exists(libpath_so):
                sopath = libpath_so
              elif os.path.exists(plainpath_so):
                sopath = plainpath_so

              if sopath:
                print('found %s in %s' % (lib, libdir))
                found_sofiles.append(sopath)
                needed_libs.remove(lib)
                found_libs.append(lib)
                continue

              if os.path.exists(libpath_a):
                print('found %s (static) in %s' % (lib, libdir))
                needed_libs.remove(lib)
                found_libs.append(lib)
                continue

          for sofile in found_sofiles:
            print('scanning dependencies for %s' % sofile)
            out = subprocess.check_output([os.environ['READELF'], '-d', sofile])
            for line in out.splitlines():
              needso = re_needso.match(line)
              if needso:
                lib = needso.group(1)
                if lib not in needed_libs and lib not in found_libs and lib not in blacklist_libs:
                  needed_libs.append(needso.group(1))

          sofiles += found_sofiles

          if needed_libs == start_needed_libs:
            raise RuntimeError('Failed to locate needed libraries!\n\t' + '\n\t'.join(needed_libs))

output = sys.argv[1]

with open(output, 'w') as f:
    f.write('\n'.join(sofiles))
